<?php declare(strict_types=1);

namespace App\Bac\Handler\RBAC;

use App\Bac\Model\RBAC\Admin;
use DbModels\RBAC\RoleAdmin;
use DbModels\RBAC\RolePermission;
use Hyperf\DbConnection\Db;

use function Hyperf\Coroutine\co;

trait CacheManager
{
    /**
     * 【协程】清除相关用户的权限缓存
     * @param array $roleIds
     * @return void
     */
    public function clearRoleRelationCache(array $roleIds): void
    {
        co(function () use ($roleIds) {
            $query = RoleAdmin::whereIn('role_id', $roleIds)->pluck('uid');
            self::doClearCache($query->toArray());
        });
    }

    /**
     * 【协程】清除权限关联用户的权限缓存
     * @param int $permissionId
     * @return void
     */
    protected function clearPermissionRelationCache(int $permissionId): void
    {
        co(function () use ($permissionId) {
            $prefix = env('DB_PREFIX', '');
            $query = RolePermission::query()->join("rbac_role_admin", 'rbac_role_permission.role_id', '=', 'rbac_role_admin.role_id')
                ->whereRaw("{$prefix}rbac_role_permission.pms_id={$permissionId}")
                ->select([Db::raw("{$prefix}rbac_role_admin.uid")]);
            self::doClearCache($query->pluck('uid')->toArray());
        });
    }

    private static function doClearCache(array $adminIds): void
    {
        $admin = make(Admin::class);
        foreach ($adminIds as $uId) {
            $admin->clearRbacCache($uId);
        }
    }


}
